package com.mywork.mvpkodeinxml.ui

import android.Manifest
import android.os.Bundle
import android.os.Environment
import android.view.View
import com.mywork.mvpkodeinxml.R
import com.mywork.mvpkodeinxml.base.ui.activity.BaseMvpActivity
import com.mywork.mvpkodeinxml.common.FILE_DOWNLOAD_PATH
import com.mywork.mvpkodeinxml.common.execute
import com.mywork.mvpkodeinxml.common.setThrottlOnClickListener
import com.mywork.mvpkodeinxml.model.response.BaseEntity
import com.mywork.mvpkodeinxml.model.response.UserListEntity
import com.mywork.mvpkodeinxml.net.DownloadFactory
import com.mywork.mvpkodeinxml.presenter.MainPresenter
import com.mywork.mvpkodeinxml.net.service.UploadService
import com.mywork.mvpkodeinxml.view.MainView
import com.mywork.retrofitfileconverter.body.ProgressResponseListener
import com.orhanobut.logger.Logger
import com.zchu.rxcache.data.CacheResult
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import org.kodein.di.Copy
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.retainedKodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import java.io.File

class MainActivity : BaseMvpActivity<MainPresenter>(), MainView, KodeinAware, View.OnClickListener,
    EasyPermissions.PermissionCallbacks {


    override val kodein: Kodein by retainedKodein {
        extend(parentKodein, copy = Copy.All)
        bind() from instance(this@MainActivity)
    }

    //Inject
    override val mPresenter: MainPresenter by instance()

    val uploadService: UploadService by instance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViews()
        DownloadFactory.setListener(object : ProgressResponseListener {
            override fun onResponseProgress(bytesRead: Long, contentLength: Long, done: Boolean) {
                mDownloadTv.text = "$bytesRead / $contentLength"
            }
        })
    }

    private fun initViews() {
        //mAbbrBtn.setOnClickListener(this)
        mAbbrBtn.setThrottlOnClickListener(this,this)
        mDownLoadBtn.setThrottlOnClickListener(this,this)
        mUpLoadBtn.setThrottlOnClickListener(this,this)
        mAddBtn.setOnClickListener(this)
        mDelBtn.setOnClickListener(this)
        mModifyBtn.setOnClickListener(this)
        mQueryBtn.setOnClickListener(this)
    }

    override fun onGetUserList(result: UserListEntity, source: String) {
        Logger.d(result.items.recordcount)
        mAbbrCodeTv.text = result.items.recordcount
        mAbbrSourceTv.text = source
        /*Thread{
            UsersDatabase.getInstance(this@MainActivity).usersDao().insert(*result.items.UserList.toTypedArray())
        }.start()*/
    }


    override fun onFileDownload(result: CacheResult<File>) {
        Logger.d("onFinish:${result.data.name},type:${result.data.extension},timestamp:${result.timestamp}},source:${result.from.name}")
        mDownloadTv.text = result.data.name
        mDownloadSourceTv.text = result.from.name
    }


    override fun onGetUsers(result: List<UserListEntity.UserItems.UserItem>) {
        Logger.d(result)
    }

    companion object {
        const val REQUEST_CODE_QRCODE_PERMISSIONS = 1
    }

    override fun onStart() {
        super.onStart()
        requestCodeQRCodePermissions()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>?) {

    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>?) {

    }

    @AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
    private fun requestCodeQRCodePermissions() {
        val perms = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (!EasyPermissions.hasPermissions(this, *perms)) {
            EasyPermissions.requestPermissions(this, "写入外置存储", REQUEST_CODE_QRCODE_PERMISSIONS, *perms)
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.mAbbrBtn -> {
                mPresenter.getUserList()
            }
            R.id.mDownLoadBtn -> {
                /*val a = mapOf(Pair("A", "1"), Pair("B", "2"), Pair("C", "3"))
                AppPrefsUtils.putHashMapData("map", a)*/

                val url =
                    "http://119.145.33.75:8099/KrsIPUI/T95Service/EmFileHandler.ashx?optag=2&userCode=120041&userPassword=&formid=49a7fc929e3f4c99b0709ac5e31ae4e5"

                //mPresenter.downLoad(url,"test.dat")
                //mPresenter.downLoad("120041", "", "49a7fc929e3f4c99b0709ac5e31ae4e5")
                val path =
                    Environment.getExternalStorageDirectory().toString() + FILE_DOWNLOAD_PATH + File.separator + "9ea862fed408469db5fbc9b3dfef1b72.dat"

                mPresenter.downLoad("120041", "", "9ea862fed408469db5fbc9b3dfef1b72", path)


                /*DownloadFactory.create(DownloadApi::class.java)
                    .download("120041", "", "3f57a08eda284a1fb571af00ee1bf40b", path)
                    .rxCache("120041" + "3f57a08eda284a1fb571af00ee1bf40b", CacheStrategy.firstRemote())
                    .execute(this, this, object : Observer<CacheResult<File>> {
                        override fun onComplete() {

                        }

                        override fun onSubscribe(d: Disposable) {

                        }

                        override fun onNext(t: CacheResult<File>) {
                            mDownloadSourceTv.text = t.from.name
                            mDownloadTv.text = t.data.name
                        }

                        override fun onError(e: Throwable) {
                            e.printStackTrace()
                        }
                    })*/

                /*DownloadFactory.create(DownloadApi::class.java)
                    .download("120041", "", "49a7fc929e3f4c99b0709ac5e31ae4e5", path)
                    .rxCache("120041" + "49a7fc929e3f4c99b0709ac5e31ae4e5", CacheStrategy.firstRemote())
                    .execute(this, this, object : Observer<CacheResult<File>> {
                        override fun onComplete() {

                        }

                        override fun onSubscribe(d: Disposable) {

                        }

                        override fun onNext(t: CacheResult<File>) {
                            mDownloadSourceTv.text = t.from.name
                            mDownloadTv.text = t.data.name
                        }

                        override fun onError(e: Throwable) {
                            e.printStackTrace()
                        }
                    })*/
            }
            R.id.mUpLoadBtn -> {
                uploadService
                    .upload("120041","","99","7ee8a8472b734f268bb473256fb1a6d3",File("/storage/emulated/0/Download/5450ae2fdef8a.jpg"))
                    .execute(this,this,object : Observer<BaseEntity>{
                        override fun onComplete() {

                        }

                        override fun onSubscribe(d: Disposable) {

                        }

                        override fun onNext(t: BaseEntity) {
                            Logger.d(t)
                        }

                        override fun onError(e: Throwable) {
                            e.printStackTrace()
                        }
                    })

                /*val b = AppPrefsUtils.getHashMapData("map")
                println(b)*/
                /*val abc = AppPrefsUtils.getHashMapData("download", FileInfo::class.java)
                Logger.d(abc)*/
                //AppPrefsUtils.remove("download")

            }
            R.id.mAddBtn -> {

            }
            R.id.mDelBtn -> {

            }
            R.id.mModifyBtn -> {

            }
            R.id.mQueryBtn -> {

            }
            else -> {
            }
        }
    }


}